<?php
namespace app\job;

use app\common\service\webscoket\CacheService;
use think\facade\Log;
use think\swoole\Websocket;
use app\webscoket\Manager;
use think\queue\Job;

/**
 * 消息发送队列
 * Class UniPush
 * @package app\jobs
 */
class SwooleTaskJob
{
    public function fire(Job $job, $data)
    {
        $job->delete();
        Log::write("异步任务来了");
        if (method_exists($this, $data['type'])) {
            $this->{$data['type']}($data['data']);
        } else {
            Log::error('任务执行失败,' . $data['type'] . '方法不存在');
        }
//        $job->delete();
    }

    public function message(array $data)
    {
        Log::write("异步任务方法来了");
        $fds = CacheService::sMembers('_ws_user4');
        $fd = $fds[0];
        $server = app()->make(Websocket::class);
//        $server = app('swoole.server');
        if ($server->isEstablished($fd)) {
            // 推送消息到 WebSocket 客户端
            $server->push($fd, json_encode(['msg'=>'我看看']));
            Log::write("在");
        }else{
            Log::write("不在");
        }

//        /** @var Server $server */
//        $server = app()->make(Websocket::class);
//        $fds = Manager::getUserIdByFds(8);
//        Log::write("fds:".print_r($fds,true));
//        foreach ($fds as $fd) {
//            $res = $server->to($fd)->push(json_encode(['code'=>200,'msg'=>'成功了吗？']));
//            Log::write("结果:".$res);
//        }
    }
}
